package com.qboot.common.utils;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.qboot.common.consts.MsgConst;
import com.qboot.common.exception.BusinessException;
import com.qboot.common.utils.AssertUtils;
import com.qboot.common.utils.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Objects;

/**
 * EasyPoi 工具类
 * https://blog.csdn.net/qq_38762237/article/details/121607927
 *
 * @author Tellsea
 * @date 2022/12/3
 */
@Slf4j
public class EasyPoiExcelUtils {

    public static void exportExcel(List<?> list, String title, Class<?> pojoClass) {
        ExportParams exportParams = new ExportParams(title, "Sheet1");
        exportParams.setAutoSize(true);
        defaultExport(list, pojoClass, title + ".xlsx", exportParams);
    }

    private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, ExportParams exportParams) {
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
        downLoadExcel(fileName, workbook);
    }

    private static void downLoadExcel(String fileName, Workbook workbook) {
        try {
            HttpServletResponse response = SpringUtils.getResponse();
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            workbook.write(response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("下载失败");
        }
    }

    public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass) {
        AssertUtils.isTrue(Objects.isNull(file), "找不到文件");
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List<T> list = null;
        try {
            list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
        } catch (NoSuchElementException e) {
            e.printStackTrace();
            throw new BusinessException("文件不能为空");
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(MsgConst.IMPORT_ERROR);
        }
        AssertUtils.isTrue(CollectionUtils.isEmpty(list), "导入数据为空");
        return list;
    }
}
